<?php
declare (strict_types = 1);

namespace app\admin\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class Setting extends Model
{
    protected $table = 'jade_option';

    protected $autoWriteTimestamp = true;

    /**
     * 修改或添加数据
     *
     * @param array $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addOrUpdateOption(array $param) : array
    {

        $option = $this->where('option_name', $param['option_name'])->find() ?? [];
        $data = $param[$param['option_name']];
        if (!$option) {
            //为空添加 获取数据
            $this->option_name = $param['option_name'];
            $this->option_value = $data;
            $res = $this->save();
            $operation = '添加成功';
        } else {
            // 有数据则修改
            $value = $option->option_value;
            $data = $data + $value;
            $option->option_value = $data;
            $res = $option->save();
            $operation = '修改成功';
        }

        return [$res, $operation];

    }


    /**
     * 获取一组配置
     *
     * @param $option_name
     * @return array|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOptionTags($option_name) : ?array
    {

        $data = $this->where('option_name', $option_name)->find() ?? [];
        return $data->option_value;

    }

    /**
     * 获取一组配置中一个数据
     *
     * @param $option_name
     * @param $option_value
     * @return string|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOptionTag($option_name, $option_value) : ?string
    {

        $data = $this->where('option_name', $option_name)->find() ?? [];
        return $data->option_value[$option_value];

    }

    /**
     * 获取设置json转数组
     *
     * @param string $value
     * @return array
     */
    public function getOptionValueAttr(string $value) : array
    {

        return json_decode($value, true);

    }

    /**
     * 获取设置数组转json
     *
     * @param string $value
     * @return array
     */
    public function setOptionValueAttr(array $value) : string
    {

        return json_encode($value);

    }

}
